package org.yh.moodpraise.schedule;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.yh.moodpraise.service.MoodService;
import org.yh.moodpraise.service.UserMoodPraiseRelService;

import java.util.Set;

/**
 * @Author: yh
 * @Date: 2020/6/21
 * @Description:
 */
@Component
@EnableScheduling
public class PraiseSaveDBJob {
    private static final String PRAISE_HASH_KEY ="moodpraise.praise.moodid";
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserMoodPraiseRelService userMoodPraiseRelService;    
    @Autowired
    MoodService moodService;
    
    @Scheduled(cron = "*/60 * * * * *")
    public void savePraiseToDB(){
        //获取被点赞的moodId
        Set<Integer> moodIds = redisTemplate.opsForSet().members(PRAISE_HASH_KEY);
        if(moodIds ==null){
            return;
        }

        for (Integer moodId : moodIds) {
          //更新点赞数
            int praiseIncrement = redisTemplate.opsForSet().size(moodId).intValue();
            if(praiseIncrement>0)
                 moodService.praiseIncrementForMq(moodId,praiseIncrement);

            //得到点赞了说说mood的用户id
            Set<Integer>uids =redisTemplate.opsForSet().members(moodId);
            if(uids !=null){
                for (Integer uid : uids) {
                    //更新说说用户关联表
                    userMoodPraiseRelService.addPraiseInfo(uid,moodId);
                }
            }
            //删除缓存 (k:moodId , v: ...userId) 数据，避免重复更新
            redisTemplate.delete(moodId);
        }
        //删除缓存（k:PRAISE_HASH_KEY , v: moodId）
        redisTemplate.delete(PRAISE_HASH_KEY);
    }
}
